const app = getApp();
//返回今天周几
export function getWeekByDate(dates) {
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate());
  let day = date.getDay();
  return show_day[day];
}
//返回今天周几,数字
export function getWeekNumByDate(dates) {
  let show_day = new Array('7', '1', '2', '3', '4', '5', '6');
  let date = new Date(dates);
  date.setDate(date.getDate());
  let day = date.getDay();
  return show_day[day];
}
//取消不做任何处理
export function showModal(obj = {
  title: '提示',
  content: '这是一个模态弹窗',
  fail: () => {}
}) {
  let wxShowModal = new Promise((resolve, reject) => {
    obj.showCancel = obj.showCancel ? obj.showCancel : false
    obj.success = (res) => {
      if (res.confirm) {
        resolve(res)
      } else if (res.cancel) {
        reject(res)
      }
    }
    wx.showModal(obj);
  })
  return wxShowModal;
}
// 显示自定义警告 
export function showToast(msg, page = 'app', time = 1500, type = 'warn') {
  if (page == 'app') {
    wx.showToast({
      mask: true,
      title: msg || 'error',
      image: '/imgs/waring.png',
      icon: 'loading',
      duration: time
    });

  } else {
    page.setData({
      showSelfToast: true,
      errorMsg: msg || 'error',
      modalBoxType: type
    });
    var expressTime = setTimeout(function () {
      clearTimeout(expressTime);
      page.setData({
        showSelfToast: false,
        modalBoxType: ''
      });
    }, time);
  }

}
export function showTips(msg, icon = 'loading', time = 1500) {
  wx.showToast({
    mask: true,
    title: msg,
    icon: icon,
    duration: time
  });
}
//数值排序，从小到大,key
export function sortToBigByKey(array, key) {
  return array.sort(function (a, b) {
    var x = a[key];
    var y = b[key];
    return x < y ? -1 : x > y ? 1 : 0;
  });
}
//数值排序，从小到大
export function sortToBig(array) {
  return array.sort(function (a, b) {
    var x = a;
    var y = b;
    return x < y ? -1 : x > y ? 1 : 0;
  });
}
//通过数字获取周
export function getWeekByNum(array) {
  let arr = [];
  array.forEach(function (item, index) {
    if (item == 1) {
      arr.push("周一");
    } else if (item == 2) {
      arr.push("周二");
    } else if (item == 3) {
      arr.push("周三");
    } else if (item == 4) {
      arr.push("周四");
    } else if (item == 5) {
      arr.push("周五");
    } else if (item == 6) {
      arr.push("周六");
    } else if (item == 7) {
      arr.push("周日");
    }
  });
  return arr;
}
// 去除左右所有空格
export function trim(str) {
  if (str) {
    str = str.replace(/(^\s*)|(\s*$)/g, "");
  } else {
    str = ''
  }

  return str;
}
// 去除所有空格
export function trim2(str) {
  if (str) {
    str = str.replace(/\s+/g, '');
  } else {
    str = ''
  }

  return str;
}
//拨打电话
export function makePhoneCall(phone) {
  if (!phone) {
    wx.showModal({
      title: '提示',
      confirmText: '确定',
      content: '未设置号码',
      success: function (res) {

      }
    })
    return;
  }
  wx.makePhoneCall({
    phoneNumber: phone, //仅为示例，并非真实的电话号码,
    fail: (res) => {
      if (res.errMsg == "makePhoneCall:fail cancel") {
        return;
      }
      wx.showModal({
        title: '是否复制号码',
        confirmText: '复制',
        content: phone,
        success: function (res) {
          if (res.confirm) {
            wx.setClipboardData({
              data: phone,
              success: function (res) {
                showTips('复制成功', 'success')
              }
            })
          }
        }
      })
    }
  })
}
// 打开地理位置
export function openLocation(latitude, longitude, address = '') {
  try {
    latitude = parseFloat(latitude);
    longitude = parseFloat(longitude);
  } catch (err) {
    showToast('经纬度格式错误')
    return;
  }
  wx.openLocation({
    latitude: latitude,
    longitude: longitude,
    address: address,
    // scale: 18,
    fail: () => {
      showToast('打开失败')
    }
  })
}
//跳转
export function nav(param) {
  console.log(param);
  if (app.tabBarPath.indexOf(param.url.split('?')[0]) >= 0) {
    wx.switchTab({
      url: param.url
    });
    return;
  }
  let str = '',
    url = '';
  if (param.data) {
    for (let key in param.data) {
      str += `&${key}=${param.data[key]}`;
    }
    str = str.replace(/^&/, '?');
  }
  url = param.url + str;
  console.log(url);
  console.log(getCurrentPages().length)
  //是否为主页
  let have = false
  app.customTabBar.list.forEach((item, index) => {
    if (url.indexOf('/' + item.pagePath) != -1) {
      have = true
    }
  })
  if (have) {
    wx.switchTab({
      url: url
    })
  } else {
    if (getCurrentPages().length >= 10) {
      wx.redirectTo({
        url: url
      })
    } else {
      wx.navigateTo({
        url: url
      })
    }
  }

}
//弹窗跳转
export function noticeNav(eventType, eventParam) {
  switch (eventType) {
    //扫码点餐页
    case 'scanCode':
      wx.navigateTo({
        url: '../queueMenu/queueMenu',
      })
      break;
      //商品分类
    case 'goodsList':
      wx.navigateTo({
        url: '../queueMenu/queueMenu?tabId=' + eventParam.id
      })
      break;
      //拨打电话
    case 'call':
      wx.makePhoneCall({
        phoneNumber: eventParam.phone,
        success: function () {
          console.log("拨打电话成功！")
        },
        fail: function () {
          console.log("拨打电话失败！")
        }
      })
      break;
      //导航前往
    case 'locNav':
      let arr = eventParam.lnglat.split(',')
      const latitude = Number(arr[1])
      const longitude = Number(arr[0])
      wx.openLocation({
        latitude,
        longitude,
        address: eventParam.address,
        scale: 18
      })
      break;
    case 'personal':
      wx.switchTab({
        url: '../my/my'
      })
      break;
    case 'queueMenu':
      wx.navigateTo({
        url: '../queueMenu/queueMenu',
      })
      break;
    case 'pickUp':
      wx.navigateTo({
        url: '../pickUp/pickUp',
      })
      break;
    case 'takeAwayMenu':
      wx.navigateTo({
        url: '../takeAwayMenu/takeAwayMenu',
      })
      break;
    case 'equityCardShop':
      wx.navigateTo({
        url: '../equityCardShop/equityCardShop',
      })
      break;
    case 'integralMall':
      wx.navigateTo({
        url: '../integralMall/integralMall',
      })
      break;
    case 'menberCard':
      wx.navigateTo({
        url: '../menberCard/menberCard',
      })
      break;
    case 'storedValue':
      wx.navigateTo({
        url: '../storedValue/storedValue',
      })
      break;
    case 'getCoupon':
      wx.navigateTo({
        url: '../coupon/getCoupon/getCoupon',
      })
      break;
    case 'accessWine':
      wx.navigateTo({
        url: '../accessWine/accessWine',
      })
      break;
    case 'collectionReward':
      wx.navigateTo({
        url: '../collectionReward/collectionReward',
      })
      break;
    case 'myOrder':
      wx.navigateTo({
        url: '../myOrder/myOrder',
      })
      break;
  }
}
//获取地址参数值
export function getUrlParam(key, str) {
  var paths = str.split('?');
  for (var i = 1; i < paths.length; i++) {
    var params = paths[i].split('&');
    for (var j = 0; j < params.length; j++) {
      var tmp = params[j].split('=');
      if (tmp[0] == key) {
        return tmp[1];
      }
    }
  }
  return ''
}
//自定义底部栏
export function editTabBar(page, change = '') {
  console.log('app.customTabBar.list:', app.customTabBar.list)
  console.log('app.globalData.tabBarSub.list:', app.globalData.tabBarSub.list)
  let old_list = app.customTabBar.list
  let new_list = old_list.filter(item => {
    for (var i = 0; i < app.globalData.tabBarSub.list.length; i++) {
      if (item.pagePath == app.globalData.tabBarSub.list[i].pagePath) {
        return item

      }
    }
  });
  console.log(new_list, 'new_list')
  let getTabBar = page.getTabBar()
  if (typeof page.getTabBar === 'function' &&
    getTabBar) {
    console.log('222--')
    if (['index', 'personal'].indexOf(change) > -1 && app.extConfig.isNew == 2) { //多商户
      console.log('多商户底部图标')
      getTabBar.setData({
        // 'tabSet.list': app.globalData.isHeadShop ? app.customTabBar.list : app.globalData.tabBarSub.list
        'tabSet.list': app.globalData.isHeadShop ? app.customTabBar.list : new_list
      })
      console.log('tabSet.list', getTabBar)
    }
    const {
      data: {
        tabSet: {
          list
        }
      }
    } = getTabBar
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = _pagePath;
    }
    let index = list.findIndex(item => item.pagePath == _pagePath)
    if(index==1){
      app.globalData.mainIndex = true
    }else{
      app.globalData.mainIndex = false
    }
    console.log('xx--', index,app.globalData.mainIndex)
    getTabBar.setData({
      selected: index,
      cartTotal: app.globalData.cartTotal
    })
  }else{
    app.globalData.mainIndex = false
    console.log("bushizhuyemian")
  }
}